package imper.engine.battle.view;

import imper.engine.battle.IModel;
import imper.engine.battle.engine.map.VisualReaderMap;
import imper.engine.entity.Position;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

import TWLSlick.BasicTWLGameState;

public class BattleView extends BasicTWLGameState
{
	IModel _model = null;

	protected VisualReaderMap _visualReaderMap;

	protected Image image;
	protected Image image2;
	protected Image image3;

	protected Position _posMouse = new Position( 0, 0 );

	protected Position _posSelect = null;

	public BattleView(IModel pModel)
	{
		_model = pModel;
		_visualReaderMap = new VisualReaderMap( _model.getMap(), 8, 15 );
	}

	@Override
	public void init( GameContainer pGameContainer , StateBasedGame pStateBasedGame ) throws SlickException
	{
		_visualReaderMap.init();
		try
		{
			image = new Image( "data/hexa/hexagone2.png" );
			image2 = new Image( "data/hexa/hexagone3.png" );
			image3 = new Image( "data/hexa/hexagone5.png" );
		}
		catch ( SlickException e )
		{
			e.printStackTrace();
		}
		// System.out.println( Math.sqrt(3.0)/2.0 * 48.0 );
	}

	@Override
	public void render( GameContainer pGameContainer , StateBasedGame pStateBasedGame , Graphics pGraphics ) throws SlickException
	{
		_visualReaderMap.setGraphics( pGraphics , new Position( 0, 0 ) );
		_visualReaderMap.read();
		// autre
		Position pos = VisualReaderMap.transformPositionInScreen( _posMouse );
		pGraphics.drawImage( image2 , pos.getPosX() , pos.getPosY() );
		// autre
		pos = VisualReaderMap.transformPositionInScreen( new Position( 5, 5 ) );
		pGraphics.drawImage( image3 , pos.getPosX() , pos.getPosY() );
		// selection
		if ( _posSelect != null )
		{
			pos = VisualReaderMap.transformPositionInScreen( _posSelect );
			pGraphics.drawImage( image3 , pos.getPosX() , pos.getPosY() );
		}
	}

	@Override
	public void update( GameContainer pGameContainer , StateBasedGame pStateBasedGame , int pGraphics ) throws SlickException
	{
		// TODO Auto-generated method stub

	}

	@Override
	public int getID()
	{
		return 0;
	}

	public void mouseClicked( int pButton , int pX , int pY , int pClickCount )
	{
		//System.out.println( pButton );
		//System.out.println( pClickCount );
		_posSelect = getPositionOnHexa( pX , pY );

		super.mouseClicked( pButton , pX , pY , pClickCount );
	}

	private Position getPositionOnHexa( int pX , int pY )
	{
		double q = (1.0 / 3.0 * Math.sqrt( 3.0 ) * (double) pX - 1 / 3 * (double) pY) / 24;
		double r = 2.0 / 3.0 * (double) pY / 24;

		return new Position( (int) q, (int) r );
	}

	public void mouseMoved( int oldx , int oldy , int pNewX , int pNewY )
	{
		_posMouse = getPositionOnHexa( pNewX , pNewY );

		super.mouseMoved( oldx , oldy , pNewX , pNewY );
	}

}
